import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import apiService, { type UploadFileInfoRequest, type OssUploadSignatureResponse } from '../services/apiService'
import { OSS_BASE_URL } from '../config'

// 定义PromptImage类型
interface PromptImage {
  id: number
  prompt_id: number
  image_url: string
  thumbnail_url?: string
  alt_text?: string
  sort_order: number
  created_at: string
}

// 定义Prompt类型
interface Prompt {
  id: number
  title: string
  description: string
  prompt: string
  category: string
  aiModel: string
  author: string
  likes: number
  createdAt: string
  isCollected?: boolean
  image?: string
  images?: PromptImage[]
}

export default function PromptDetailPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const { token, isAuthenticated } = useAuth()
  const [prompt, setPrompt] = useState<Prompt | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [copiedId, setCopiedId] = useState<number | null>(null)
  const [collectingId, setCollectingId] = useState<number | null>(null)
  const [collectMessage, setCollectMessage] = useState<string>('')
  const [isEditing, setIsEditing] = useState(false)
  const [editedPrompt, setEditedPrompt] = useState<Prompt | null>(null)
  const [uploadedImage, setUploadedImage] = useState<string | null>(null)
  const [ossConfig, setOssConfig] = useState<OssUploadSignatureResponse | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 获取图片尺寸函数
  const getImageDimensions = (file: File): Promise<{width: number, height: number}> => {
    return new Promise((resolve) => {
      const img = new Image()
      img.onload = () => {
        resolve({width: img.width, height: img.height})
      }
      img.src = URL.createObjectURL(file)
    })
  }

  // 复制到剪贴板函数
  const copyToClipboard = async (text: string, promptId: number) => {
    try {
      await navigator.clipboard.writeText(text)
      setCopiedId(promptId)
      // 2秒后重置状态
      setTimeout(() => setCopiedId(null), 2000)
    } catch (err) {
      console.error('复制失败:', err)
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      setCopiedId(promptId)
      setTimeout(() => setCopiedId(null), 2000)
    }
  }

  // 开始编辑
  const startEdit = async () => {
    setIsEditing(true)
    setEditedPrompt({ ...prompt! })
    setUploadedImage(prompt?.image || null)
    console.log("oss upload config")
    setError('') // 清除之前的错误

    // 获取OSS上传配置
    try {
      const config = await apiService.getOssUploadSignature()
      setOssConfig(config)
    } catch (error) {
      console.error('获取OSS配置失败:', error)
    }
  }

  // 取消编辑
  const cancelEdit = () => {
    setIsEditing(false)
    setEditedPrompt(null)
    setUploadedImage(null)
    setOssConfig(null)
  }

  // 保存编辑
  const saveEdit = async () => {
    if (!editedPrompt) return
    
    setError('') // 清除之前的错误
    let uploadData: any[] = [] // 初始化 uploadData 数组

    try {
      let imageUrl = prompt?.image // 保持原有图片URL
      
      // 如果有新上传的图片，先上传到OSS
      if (uploadedImage && uploadedImage.startsWith('data:')) {
        // 将base64转换为File对象
        const response = await fetch(uploadedImage)
        const blob = await response.blob()
        const file = new File([blob], 'image.jpg', { type: blob.type })
        
        // 使用预先获取的OSS配置
        if (!ossConfig) {
          throw new Error('OSS配置未准备好，请重新进入编辑模式')
        }
        
        // 上传文件到OSS
        const fileName = await apiService.uploadFileToOss(file, ossConfig)
        if (!fileName) {
          throw new Error('图片上传失败')
        }
        
        // 上传文件信息到服务器
        const dimensions = await getImageDimensions(file)
        uploadData = [{
          image_url: fileName,
          thumbnail_url: fileName,
          alt_text: null,
          sort_order: 0,
          prompt_id: parseInt(id || '0'),
          created_at: new Date().toISOString()
        }]

      } else if (uploadedImage === null) {
        // 如果删除了图片
        imageUrl = undefined
      }
      
      // 保存编辑后的prompt
      const saveResponse = await fetch(`http://localhost:8080/api/v1/prompts/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          title: editedPrompt.title,
          content: editedPrompt.prompt,
          description: editedPrompt.description,
          images: uploadData,
          // 如果有图片URL，可以在这里添加图片相关字段
          // 注意：根据API文档，可能需要调整字段名
        })
      })
      
      if (!saveResponse.ok) {
        throw new Error('保存失败')
      }
      
      const saveData = await saveResponse.json()
      if (saveData.code === 1) {
        // 更新本地状态
        setPrompt({
          ...editedPrompt,
          image: imageUrl
        })
        setIsEditing(false)
        setEditedPrompt(null)
        setUploadedImage(null)
      } else {
        throw new Error(saveData.error || '保存失败')
      }
    } catch (err) {
      console.error('保存失败:', err)
      setError(err instanceof Error ? err.message : '保存失败，请重试')
    }
  }

  // 处理图片上传
  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件')
        return
      }
      
      // 检查文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        alert('图片大小不能超过5MB')
        return
      }
      
      const reader = new FileReader()
      reader.onload = (e) => {
        const result = e.target?.result as string
        setUploadedImage(result)
      }
      reader.readAsDataURL(file)
    }
  }

  // 收藏/取消收藏函数
  const toggleCollect = async (promptId: number, isCurrentlyCollected: boolean) => {
    try {
      setCollectingId(promptId)
      
      const url = `http://localhost:8080/api/v1/prompts/${promptId}/collect`
      const method = isCurrentlyCollected ? 'DELETE' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...(token && { 'Authorization': `Bearer ${token}` })
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      
      if (data.code === 1) {
        // 更新本地状态
        setPrompt(prevPrompt => 
          prevPrompt ? { ...prevPrompt, isCollected: !isCurrentlyCollected } : null
        )
        // 显示收藏成功消息
        const successMsg = !isCurrentlyCollected ? '收藏成功！' : '取消收藏成功！'
        setCollectMessage(successMsg)
        // 3秒后清空消息
        setTimeout(() => setCollectMessage(''), 3000)
      } else {
        throw new Error(data.error || '操作失败')
      }
    } catch (err) {
      console.error('收藏操作失败:', err)
      // 如果没有token，提示用户登录
      if (!isAuthenticated) {
        setCollectMessage('请先登录后再进行收藏操作')
        // 3秒后清空消息
        setTimeout(() => setCollectMessage(''), 3000)
      } else {
        const errorMsg = err instanceof Error ? err.message : '收藏操作失败，请稍后重试'
        setCollectMessage(errorMsg)
        // 3秒后清空消息
        setTimeout(() => setCollectMessage(''), 3000)
      }
    } finally {
      setCollectingId(null)
    }
  }

  // 获取单个prompt详情
  const fetchPromptDetail = async () => {
    try {
      setLoading(true)
      setError('')
      
      const response = await fetch(`http://localhost:8080/api/v1/prompts/${id}`)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      
      if (data.code === 1) {
        // 转换API数据格式
        const transformedPrompt = {
          id: data.data.prompt.id,
          title: data.data.prompt.title,
          description: data.data.prompt.description,
          prompt: data.data.prompt.content,
          category: data.data.prompt.category?.name || '未分类',
          aiModel: data.data.prompt.ai_model?.name || '未知模型',
          author: data.data.prompt.user?.username || '匿名',
          likes: data.data.prompt.like_count || 0,
          createdAt: new Date(data.data.prompt.created_at).toLocaleDateString('zh-CN'),
          isCollected: data.data.prompt.is_collected || false,
          images: data.data.prompt.images || []
        }
        
        setPrompt(transformedPrompt)
      } else {
        throw new Error(data.error || '获取数据失败')
      }
    } catch (err) {
      console.error('获取prompt详情失败:', err)
      setError(err instanceof Error ? err.message : '网络错误，请稍后重试')
      
      // 如果API调用失败，使用模拟数据作为降级方案
      if (id) {
        setPrompt({
          id: parseInt(id),
          title: "科幻城市风景",
          description: "生成未来科幻城市的壮观景象，包含霓虹灯、飞行汽车和全息广告等元素",
          prompt: "A futuristic cyberpunk cityscape at night, neon lights reflecting on wet streets, flying cars, towering skyscrapers with holographic advertisements, highly detailed, 8k resolution, cinematic lighting, atmospheric perspective",
          category: "风景",
          aiModel: "Midjourney",
          author: "张三",
          likes: 128,
          createdAt: "2024-01-15",
          isCollected: false
        })
      }
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (id) {
      fetchPromptDetail()
    } else {
      setError('无效的prompt ID')
      setLoading(false)
    }
  }, [id])

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container py-8">
          <div className="flex justify-center items-center py-12">
            <div className="text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
              <p className="text-muted">正在加载详情...</p>
            </div>
          </div>
        </div>
      </div>
    )
  }

  if (!prompt && !loading) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container py-8">
          <p className="text-red-600">Prompt不存在</p>
        </div>
      </div>
    )
  }

  if (!prompt) {
    return null
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="container py-8">
        {/* 返回按钮 */}
        <div className="mb-6">
          <button 
            onClick={() => navigate('/')}
            className="btn btn-outline btn-sm"
          >
            ← 返回首页
          </button>
        </div>

        {/* 详情卡片 */}
        <div className="max-w-4xl mx-auto">
          <div className="card">
            <div className="card-header">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center space-x-4">
                  {isEditing ? (
                    <input
                      type="text"
                      value={editedPrompt?.title || ''}
                      onChange={(e) => setEditedPrompt(prev => prev ? {...prev, title: e.target.value} : null)}
                      className="text-3xl font-bold bg-transparent border-b-2 border-primary focus:outline-none focus:border-primary-dark"
                    />
                  ) : (
                    <h1 className="text-3xl font-bold">{prompt.title}</h1>
                  )}
                  
                  {isAuthenticated && (
                    <div className="flex items-center space-x-2">
                      {isEditing ? (
                        <>
                          <button
                            onClick={saveEdit}
                            className="btn btn-primary btn-sm"
                          >
                            保存
                          </button>
                          <button
                            onClick={cancelEdit}
                            className="btn btn-outline btn-sm"
                          >
                            取消
                          </button>
                          {error && (
                            <span className="text-red-600 text-sm">{error}</span>
                          )}
                        </>
                      ) : (
                        <button
                          onClick={startEdit}
                          className="btn btn-outline btn-sm"
                        >
                          编辑
                        </button>
                      )}
                    </div>
                  )}
                </div>
                <div className="flex items-center space-x-2 text-sm text-muted">
                  <span>👍 {prompt.likes}</span>
                  <span>📅 {prompt.createdAt}</span>
                </div>
              </div>
              
              {/* Images 显示区域 */}
              {prompt.images && prompt.images.length > 0 && (
                <div className="mb-6">
                  <h3 className="text-lg font-semibold mb-3">相关图片</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {prompt.images
                      .sort((a, b) => a.sort_order - b.sort_order)
                      .map((image) => (
                        <div key={image.id} className="relative group">
                          <img
                            src={image.thumbnail_url || image.image_url}  
                            alt={image.alt_text || `图片 ${image.id}`}
                            className="w-full h-48 object-cover rounded-lg border hover:shadow-lg transition-shadow cursor-pointer"
                            onClick={() => {
                              // 点击缩略图显示大图
                              const modal = document.createElement('div')
                              modal.className = 'fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50'
                              modal.onclick = () => modal.remove()
                              const img = document.createElement('img')
                              img.src = image.image_url
                              img.className = 'max-w-full max-h-full object-contain'
                              img.alt = image.alt_text || `图片 ${image.id}`
                              modal.appendChild(img)
                              document.body.appendChild(modal)
                            }}
                          />
                          {image.alt_text && (
                            <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white text-sm p-2 rounded-b-lg opacity-0 group-hover:opacity-100 transition-opacity">
                              {image.alt_text}
                            </div>
                          )}
                        </div>
                      ))
                    }
                  </div>
                </div>
              )}
              
              <div className="flex items-center space-x-4 mb-4">
                <span className="text-muted">作者: {prompt.author}</span>
                <div className="flex flex-wrap gap-2">
                  <span className="px-3 py-1 bg-primary-light text-sm rounded-full">
                    {prompt.category}
                  </span>
                  <span className="px-3 py-1 bg-secondary text-sm rounded-full">
                    {prompt.aiModel}
                  </span>
                </div>
              </div>
              
              {isEditing ? (
                <textarea
                  value={editedPrompt?.description || ''}
                  onChange={(e) => setEditedPrompt(prev => prev ? {...prev, description: e.target.value} : null)}
                  className="w-full text-lg text-muted mb-6 bg-transparent border border-gray-300 rounded p-2 focus:outline-none focus:border-primary"
                  rows={3}
                  placeholder="输入描述..."
                />
              ) : (
                <p className="text-lg text-muted mb-6">{prompt.description}</p>
              )}
              
              {/* 图片显示和上传区域 */}
              {(prompt.image || uploadedImage || isEditing) && (
                <div className="mb-6">
                  <h3 className="text-lg font-semibold mb-3">图片</h3>
                  <div className="relative">
                    {(uploadedImage || prompt.image) && (
                      <img
                        src={uploadedImage || prompt.image}
                        alt="Prompt 图片"
                        className="max-w-full h-auto rounded-lg border"
                        style={{ maxHeight: '400px' }}
                      />
                    )}
                    
                    {isEditing && (
                      <div className="mt-4">
                        <input
                          ref={fileInputRef}
                          type="file"
                          accept="image/*"
                          onChange={handleImageUpload}
                          className="hidden"
                        />
                        <div className="flex items-center space-x-2">
                          <button
                            onClick={() => fileInputRef.current?.click()}
                            className="btn btn-outline btn-sm"
                          >
                            {uploadedImage || prompt.image ? '更换图片' : '上传图片'}
                          </button>
                          {(uploadedImage || prompt.image) && (
                            <button
                              onClick={() => setUploadedImage(null)}
                              className="btn btn-outline btn-sm text-red-600 hover:bg-red-50"
                            >
                              删除图片
                            </button>
                          )}
                        </div>
                        <p className="text-sm text-muted mt-2">支持 JPG、PNG、GIF 格式，最大 5MB</p>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
            
            <div className="card-content">
              <div className="mb-6">
                <h2 className="text-xl font-semibold mb-3">Prompt 内容</h2>
                {isEditing ? (
                  <textarea
                    value={editedPrompt?.prompt || ''}
                    onChange={(e) => setEditedPrompt(prev => prev ? {...prev, prompt: e.target.value} : null)}
                    className="w-full bg-muted p-4 rounded-lg border text-sm font-mono focus:outline-none focus:border-primary"
                    rows={8}
                    placeholder="输入 Prompt 内容..."
                  />
                ) : (
                  <div className="bg-muted p-4 rounded-lg border">
                    <code className="text-sm font-mono whitespace-pre-wrap break-words">
                      {prompt.prompt}
                    </code>
                  </div>
                )}
              </div>
              
              {/* 操作按钮 */}
              <div className="flex flex-wrap gap-3">
                <button 
                  className={`btn transition-all duration-200 ${
                    copiedId === prompt.id 
                      ? 'btn-success' 
                      : 'btn-primary'
                  }`}
                  onClick={() => copyToClipboard(prompt.prompt, prompt.id)}
                >
                  {copiedId === prompt.id ? '已复制!' : '复制 Prompt'}
                </button>
                
                <button 
                  className={`btn transition-all duration-200 ${
                    prompt.isCollected 
                      ? 'btn-warning' 
                      : 'btn-outline'
                  } ${
                    collectingId === prompt.id ? 'loading' : ''
                  }`}
                  onClick={() => toggleCollect(prompt.id, prompt.isCollected || false)}
                  disabled={collectingId === prompt.id}
                >
                  {collectingId === prompt.id 
                    ? '处理中...' 
                    : prompt.isCollected 
                      ? '已收藏' 
                      : '收藏'
                  }
                </button>
                
                <button 
                  className="btn btn-outline"
                  onClick={() => {
                    const shareUrl = window.location.href
                    copyToClipboard(shareUrl, prompt.id)
                  }}
                >
                  分享链接
                </button>
                
                {/* 收藏结果显示 */}
                {collectMessage && (
                  <span className={`text-sm px-3 py-1 rounded-full ${
                    collectMessage.includes('成功') 
                      ? 'text-green-600 bg-green-100' 
                      : 'text-red-600 bg-red-100'
                  }`}>
                    {collectMessage}
                  </span>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}